/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.ap.entity.Income;
import com.jeeplus.modules.ap.mapper.IncomeMapper;
import com.jeeplus.modules.ap.entity.EarningsDetail;
import com.jeeplus.modules.ap.mapper.EarningsDetailMapper;

/**
 * 收入Service
 * @author slD
 * @version 2017-11-30
 */
@Service
@Transactional(readOnly = true)
public class IncomeService extends CrudService<IncomeMapper, Income> {

	@Autowired
	private EarningsDetailMapper earningsDetailMapper;
	
	public Income get(String id) {
		Income income = super.get(id);
		income.setEarningsDetailList(earningsDetailMapper.findList(new EarningsDetail(income)));
		return income;
	}
	
	public List<Income> findList(Income income) {
		return super.findList(income);
	}
	
	public Page<Income> findPage(Page<Income> page, Income income) {
		return super.findPage(page, income);
	}
	
	@Transactional(readOnly = false)
	public void save(Income income) {
		super.save(income);
		for (EarningsDetail earningsDetail : income.getEarningsDetailList()){
			if (earningsDetail.getId() == null){
				continue;
			}
			if (EarningsDetail.DEL_FLAG_NORMAL.equals(earningsDetail.getDelFlag())){
				if (StringUtils.isBlank(earningsDetail.getId())){
					earningsDetail.setIncome(income);
					earningsDetail.preInsert();
					earningsDetailMapper.insert(earningsDetail);
				}else{
					earningsDetail.preUpdate();
					earningsDetailMapper.update(earningsDetail);
				}
			}else{
				earningsDetailMapper.delete(earningsDetail);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Income income) {
		super.delete(income);
		earningsDetailMapper.delete(new EarningsDetail(income));
	}
	
}